package me.zhengjie.modules.insurance.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.insurance.mapper.InsuredApplyDocMapper;
import me.zhengjie.modules.insurance.util.InputStreamFile;
import me.zhengjie.modules.insurance.util.ZipUtil;
import me.zhengjie.service.LocalStorageService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 案件文档下载处理
 *
 * @author HeHui
 * @date 2022-01-14 23:57
 */
@Component
@RequiredArgsConstructor
public class CaseDocsDownloadHandler {

    private final InsuredApplyDocMapper applyDocMapper;


    /**
     * 下载
     *
     * @param response 响应
     * @param id       id
     * @return {@link HttpServletResponse}
     */
    public Void down(HttpServletResponse response, long id) throws IOException {
        List<String> docFiles = applyDocMapper.getCaseDocFile(id);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
            "attachment;fileName=" + URLEncoder.encode("案件[" + id + "]主要资料.zip", "UTF-8"));// 设置文件名

        if (CollUtil.isEmpty(docFiles)) {
            InputStreamFile empty = new InputStreamFile(IoUtil.toStream("无主要资料", StandardCharsets.UTF_8), "主要资料");
            ZipUtil.zip(outputStream, empty);
            return null;
        }

        InputStreamFile[] streamFiles = docFiles.stream().map(File::new).map(file -> new InputStreamFile(IoUtil.toStream(file), file.getName())).toArray(InputStreamFile[]::new);
        ZipUtil.zip(outputStream, streamFiles);
        return null;

    }
}
